﻿using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Text.Json;
using Todo.DAO.Dapper;
using TodoListWebApi.Models;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace TodoListWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TodoController : ControllerBase
    {
        private readonly JsonSerializerOptions _jsonOptions;
        private readonly TodoRepository _todoRepository;
        private readonly IMapper _mapper;

        public TodoController(TodoRepository todoRepository, IOptions<JsonSerializerOptions> jsonOptions, IMapper mapper)
        {
            _todoRepository = todoRepository;
            _mapper = mapper;
            _jsonOptions = jsonOptions.Value;
        }



        // GET: api/<TodoController>
        [HttpGet]
        public async Task<string> Get()
        {
            var todos = await _todoRepository.GetTodoListAsync();

            // 带格式化选项的高级用法
            var options = new JsonSerializerOptions
            {
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, // 中文不转义
                WriteIndented = true, // 格式化输出
                NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 驼峰命名
                Converters =
                {
                    new System.Text.Json.Serialization.JsonStringEnumConverter() // 枚举转字符串
                }
            };

            
            return JsonSerializer.Serialize(todos, options);
        }

        // GET api/<TodoController>/5
        [HttpGet("{id}")]
        public async Task<TodoModel> Get(int id)
        {
            var todo = await _todoRepository.GetTodoItemById(id);
            var a = JsonSerializer.Serialize(todo, _jsonOptions);
            var a1 = JsonSerializer.Serialize(todo);
            var ret = _mapper.Map<TodoModel>(todo);
            return ret;
        }

        // POST api/<TodoController>
        [HttpPost]
        public void Post([FromBody] ToDoReq req)
        {

        }

        // PUT api/<TodoController>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/<TodoController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
